<template>
  <div class="file-analyze-container">
    <h2>AI文件分析</h2>
    
    <el-card class="analyze-card">
      <template #header>
        <div class="card-header">
          <span>上传文件并分析</span>
          <el-tag type="info">支持PDF、DOC、DOCX、TXT等格式，最大10MB</el-tag>
        </div>
      </template>
      
      <div class="upload-section">
        <file-upload
          ref="fileUploadRef"
          upload-type="file"
          file-type="document"
          :auto-upload="false"
          button-text="选择文件"
          upload-button-text="上传并分析"
          :limit="1"
          :multiple="false"
          accept=".pdf,.doc,.docx,.txt"
          :max-size="10"
          :drag="true"
          tip="支持PDF、DOC、DOCX、TXT等格式，最大10MB"
          @success="handleUploadSuccess"
        />
      </div>
      
      <div class="question-section" v-if="fileUploaded">
        <h3>请输入关于文件的问题</h3>
        <el-form :model="analyzeForm" ref="analyzeFormRef">
          <el-form-item prop="question">
            <el-input
              v-model="analyzeForm.question"
              type="textarea"
              :rows="3"
              placeholder="请输入您想问的问题，例如：请总结这份文档的主要内容"
              :maxlength="1000"
              show-word-limit
            ></el-input>
          </el-form-item>
          
          <el-form-item prop="model">
            <el-select v-model="analyzeForm.model" placeholder="请选择AI模型">
              <el-option label="OpenAI" value="openai"></el-option>
              <el-option label="通义千问" value="tongyi"></el-option>
              <el-option label="讯飞星火" value="xunfei"></el-option>
              <el-option label="文心一言" value="qianfan"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleAnalyze" :loading="analyzing">分析文件</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="result-section" v-if="analyzeResult">
        <h3>分析结果</h3>
        <div class="result-content" v-html="formatResult(analyzeResult.analysis)"></div>
        
        <div class="file-info">
          <h4>文件信息</h4>
          <p><strong>文件URL：</strong><a :href="analyzeResult.fileUrl" target="_blank">{{ analyzeResult.fileUrl }}</a></p>
          <p><strong>使用模型：</strong>{{ getModelName(analyzeResult.model) }}</p>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { marked } from 'marked';
import FileUpload from '../../components/upload/FileUpload.vue';
import { analyzeFile } from '../../services/upload';
import { useUserStore } from '../../stores/user';

const router = useRouter();
const userStore = useUserStore();
const fileUploadRef = ref();
const fileUploaded = ref(false);
const uploadedFile = ref<File | null>(null);
const analyzing = ref(false);
const analyzeResult = ref<any>(null);

// 检查用户是否已登录
if (!userStore.isAuthenticated) {
  ElMessage.warning('请先登录后再使用文件分析功能');
  router.push('/login');
}

const analyzeForm = reactive({
  question: '',
  model: 'openai'
});

// 处理文件上传成功
const handleUploadSuccess = (results: any[]) => {
  if (results && results.length > 0) {
    const result = results[0];
    fileUploaded.value = true;
    uploadedFile.value = fileUploadRef.value.fileList[0]?.raw || null;
    ElMessage.success('文件上传成功');
  }
};

// 分析文件
const handleAnalyze = async () => {
  if (!uploadedFile.value) {
    ElMessage.warning('请先上传文件');
    return;
  }
  
  if (!analyzeForm.question.trim()) {
    ElMessage.warning('请输入问题');
    return;
  }
  
  analyzing.value = true;
  
  try {
    const res = await analyzeFile(
      uploadedFile.value,
      analyzeForm.question,
      analyzeForm.model
    );
    
    analyzeResult.value = res.data;
    ElMessage.success('分析完成');
  } catch (error: any) {
    ElMessage.error(error.message || '分析失败');
  } finally {
    analyzing.value = false;
  }
};

// 格式化分析结果，将markdown转换为HTML
const formatResult = (content: string) => {
  if (!content) return '';
  return marked(content);
};

// 获取模型名称
const getModelName = (model: string) => {
  const modelMap: Record<string, string> = {
    'openai': 'OpenAI',
    'tongyi': '通义千问',
    'xunfei': '讯飞星火',
    'qianfan': '文心一言'
  };
  
  return modelMap[model] || model;
};
</script>

<style scoped>
.file-analyze-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #303133;
}

.analyze-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-section {
  margin-bottom: 20px;
}

.question-section {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e6e6e6;
}

.question-section h3 {
  margin-bottom: 15px;
  color: #303133;
}

.result-section {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e6e6e6;
}

.result-section h3 {
  margin-bottom: 15px;
  color: #303133;
}

.result-content {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  border: 1px solid #e6e6e6;
  margin-bottom: 20px;
  line-height: 1.6;
}

.file-info {
  margin-top: 20px;
  padding: 15px;
  background-color: #f0f9eb;
  border-radius: 8px;
  border: 1px solid #e1f3d8;
}

.file-info h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #67c23a;
}

.file-info p {
  margin: 5px 0;
}

:deep(.markdown-body) {
  font-size: 14px;
}

:deep(pre) {
  background-color: #f6f8fa;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
}

:deep(code) {
  font-family: Consolas, Monaco, 'Andale Mono', monospace;
}
</style> 